<template>
  <view class="result-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-back" @tap="goBack">
        <text class="iconfont icon-back">←</text>
      </view>
      <view class="navbar-content">
        <text class="navbar-title">测试历史</text>
      </view>
    </view>

    <!-- 历史记录列表 -->
    <view class="history-list" v-if="historyList.length > 0">
      <view class="history-item" v-for="item in historyList" :key="item.id" @tap="viewDetail(item)">
        <view class="item-header">
          <view class="test-type">
            <text class="type-icon">{{ getTypeIcon(item.type) }}</text>
            <text class="type-name">{{ getTypeName(item.type) }}</text>
          </view>
          <view class="test-date">{{ formatDate(item.date) }}</view>
        </view>
        
        <view class="item-content">
          <view class="score-info">
            <text class="score-number">{{ item.score }}</text>
            <text class="score-label">分</text>
          </view>
          <view class="level-info">
            <view class="level-badge" :class="getLevelClass(item.type, item.score)">
              <text class="level-text">{{ item.level }}</text>
            </view>
          </view>
        </view>
        
        <view class="item-actions">
          <text class="view-detail">查看详情 ></text>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-else>
      <view class="empty-icon">📊</view>
      <text class="empty-title">暂无测试记录</text>
      <text class="empty-desc">完成测试后，结果将显示在这里</text>
      <button class="go-test-btn" @tap="goToTest">去测试</button>
    </view>

    <!-- 详情弹窗 -->
    <view class="detail-modal" v-if="showDetail" @tap="closeDetail">
      <view class="modal-content" @tap.stop>
        <view class="modal-header">
          <text class="modal-title">{{ getTypeName(selectedItem.type) }}详情</text>
          <text class="modal-close" @tap="closeDetail">×</text>
        </view>
        
        <view class="modal-body">
          <view class="detail-score">
            <text class="detail-score-number">{{ selectedItem.score }}</text>
            <text class="detail-score-label">分</text>
          </view>
          
          <view class="detail-level" :class="getLevelClass(selectedItem.type, selectedItem.score)">
            <text class="detail-level-text">{{ selectedItem.level }}</text>
          </view>
          
          <view class="detail-date">
            <text class="date-label">测试时间：</text>
            <text class="date-value">{{ formatDateTime(selectedItem.date) }}</text>
          </view>
          
          <view class="detail-suggestions">
            <text class="suggestions-title">建议</text>
            <view class="suggestions-list">
              <text class="suggestion-item" v-for="suggestion in getSuggestions(selectedItem)" :key="suggestion">
                • {{ suggestion }}
              </text>
            </view>
          </view>
        </view>
        
        <view class="modal-actions">
          <button class="delete-btn" @tap="deleteRecord">删除记录</button>
          <button class="retest-btn" @tap="retakeTest">重新测试</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      historyList: [],
      showDetail: false,
      selectedItem: null
    }
  },
  
  onLoad() {
    this.loadHistory()
  },
  
  onShow() {
    this.loadHistory()
  },
  
  methods: {
    loadHistory() {
      try {
        const history = uni.getStorageSync('test_history') || []
        this.historyList = history.sort((a, b) => new Date(b.date) - new Date(a.date))
      } catch (e) {
        console.error('加载历史记录失败:', e)
        this.historyList = []
      }
    },
    
    goBack() {
      uni.navigateBack()
    },
    
    goToTest() {
      uni.navigateTo({
        url: '/pages/test/test'
      })
    },
    
    getTypeIcon(type) {
      const icons = {
        anxiety: '😰',
        stress: '😤',
        sleep: '😴',
        depression: '😔'
      }
      return icons[type] || '📝'
    },
    
    getTypeName(type) {
      const names = {
        anxiety: '焦虑测试',
        stress: '压力测评',
        sleep: '睡眠质量',
        depression: '抑郁测试'
      }
      return names[type] || '心理测试'
    },
    
    getLevelClass(type, score) {
      if (type === 'anxiety') {
        if (score <= 4) return 'level-low'
        if (score <= 9) return 'level-mild'
        if (score <= 14) return 'level-moderate'
        return 'level-high'
      } else if (type === 'stress') {
        if (score <= 13) return 'level-low'
        if (score <= 26) return 'level-moderate'
        return 'level-high'
      } else if (type === 'sleep') {
        if (score <= 5) return 'level-good'
        if (score <= 10) return 'level-fair'
        if (score <= 15) return 'level-poor'
        return 'level-bad'
      }
      return 'level-normal'
    },
    
    formatDate(dateStr) {
      const date = new Date(dateStr)
      const now = new Date()
      const diff = now - date
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      
      if (days === 0) return '今天'
      if (days === 1) return '昨天'
      if (days < 7) return `${days}天前`
      
      return `${date.getMonth() + 1}月${date.getDate()}日`
    },
    
    formatDateTime(dateStr) {
      const date = new Date(dateStr)
      return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    },
    
    viewDetail(item) {
      this.selectedItem = item
      this.showDetail = true
    },
    
    closeDetail() {
      this.showDetail = false
      this.selectedItem = null
    },
    
    getSuggestions(item) {
      const { type, score } = item
      
      if (type === 'anxiety') {
        if (score <= 4) {
          return ['保持规律的作息时间', '适当进行体育锻炼', '学习放松技巧如深呼吸']
        } else if (score <= 9) {
          return ['尝试冥想或正念练习', '与朋友家人分享感受', '避免过量咖啡因摄入', '建立健康的生活习惯']
        } else if (score <= 14) {
          return ['考虑寻求心理咨询师帮助', '学习压力管理技巧', '规律运动，如瑜伽、散步', '避免过度使用社交媒体']
        } else {
          return ['尽快咨询心理健康专家', '考虑专业的心理治疗', '与医生讨论治疗方案', '寻求家人朋友的支持']
        }
      } else if (type === 'stress') {
        if (score <= 13) {
          return ['保持现有的良好状态', '继续使用有效的应对策略', '适当挑战自己，促进成长']
        } else if (score <= 26) {
          return ['学习时间管理技巧', '建立规律的运动习惯', '培养兴趣爱好放松身心', '与朋友家人保持良好沟通']
        } else {
          return ['考虑寻求专业心理咨询', '学习压力管理技巧', '调整工作和生活节奏', '建立强有力的社会支持网络']
        }
      } else if (type === 'sleep') {
        if (score <= 5) {
          return ['保持现有的良好睡眠习惯', '维持规律的作息时间', '继续保持舒适的睡眠环境']
        } else if (score <= 10) {
          return ['建立固定的睡前例行程序', '避免睡前使用电子设备', '保持卧室安静、黑暗、凉爽']
        } else if (score <= 15) {
          return ['严格遵守睡眠时间表', '创造更好的睡眠环境', '学习放松技巧如深呼吸', '避免白天长时间午睡']
        } else {
          return ['尽快咨询睡眠专科医生', '进行详细的睡眠评估', '考虑睡眠监测检查', '评估是否存在睡眠障碍']
        }
      }
      
      return ['建议咨询专业人士', '保持健康的生活方式', '定期进行自我评估']
    },
    
    deleteRecord() {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这条测试记录吗？',
        success: (res) => {
          if (res.confirm) {
            try {
              let history = uni.getStorageSync('test_history') || []
              history = history.filter(item => item.id !== this.selectedItem.id)
              uni.setStorageSync('test_history', history)
              
              this.loadHistory()
              this.closeDetail()
              
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              })
            } catch (e) {
              uni.showToast({
                title: '删除失败',
                icon: 'error'
              })
            }
          }
        }
      })
    },
    
    retakeTest() {
      const testPages = {
        anxiety: '/pages/test/anxiety',
        stress: '/pages/test/stress',
        sleep: '/pages/test/sleep'
      }
      
      const url = testPages[this.selectedItem.type]
      if (url) {
        uni.navigateTo({ url })
        this.closeDetail()
      }
    }
  }
}
</script>

<style scoped>
.result-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
}

/* 导航栏 */
.custom-navbar {
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
  padding: 88rpx 40rpx 40rpx;
  color: white;
  display: flex;
  align-items: center;
}

.navbar-back {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
}

.navbar-back .iconfont {
  font-size: 36rpx;
}

.navbar-content {
  flex: 1;
  text-align: center;
}

.navbar-title {
  font-size: 36rpx;
  font-weight: 600;
}

/* 历史记录列表 */
.history-list {
  padding: 30rpx;
}

.history-item {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.test-type {
  display: flex;
  align-items: center;
}

.type-icon {
  font-size: 32rpx;
  margin-right: 10rpx;
}

.type-name {
  font-size: 32rpx;
  font-weight: 600;
  color: var(--text-primary);
}

.test-date {
  font-size: 24rpx;
  color: var(--text-tertiary);
}

.item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.score-info {
  display: flex;
  align-items: baseline;
}

.score-number {
  font-size: 48rpx;
  font-weight: 600;
  color: var(--primary-color);
}

.score-label {
  font-size: 24rpx;
  color: var(--text-secondary);
  margin-left: 5rpx;
}

.level-badge {
  padding: 8rpx 16rpx;
  border-radius: 12rpx;
  font-size: 24rpx;
}

.level-low { background: #d4edda; color: #155724; }
.level-mild { background: #fff3cd; color: #856404; }
.level-moderate { background: #f8d7da; color: #721c24; }
.level-high { background: #f5c6cb; color: #721c24; }
.level-good { background: #d4edda; color: #155724; }
.level-fair { background: #d1ecf1; color: #0c5460; }
.level-poor { background: #fff3cd; color: #856404; }
.level-bad { background: #f8d7da; color: #721c24; }
.level-normal { background: #e2e3e5; color: #383d41; }

.item-actions {
  text-align: right;
}

.view-detail {
  font-size: 24rpx;
  color: var(--primary-color);
}

/* 空状态 */
.empty-state {
  padding: 120rpx 60rpx;
  text-align: center;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 30rpx;
}

.empty-title {
  font-size: 36rpx;
  font-weight: 600;
  color: var(--text-primary);
  display: block;
  margin-bottom: 15rpx;
}

.empty-desc {
  font-size: 28rpx;
  color: var(--text-secondary);
  display: block;
  margin-bottom: 40rpx;
}

.go-test-btn {
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
  color: white;
  border: none;
  border-radius: 16rpx;
  padding: 24rpx 48rpx;
  font-size: 28rpx;
}

/* 详情弹窗 */
.detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 24rpx;
  width: 90%;
  max-width: 600rpx;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx 40rpx 20rpx;
  border-bottom: 2rpx solid var(--border-color);
}

.modal-title {
  font-size: 36rpx;
  font-weight: 600;
  color: var(--text-primary);
}

.modal-close {
  font-size: 48rpx;
  color: var(--text-tertiary);
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-body {
  padding: 40rpx;
  text-align: center;
}

.detail-score {
  margin-bottom: 20rpx;
}

.detail-score-number {
  font-size: 80rpx;
  font-weight: 600;
  color: var(--primary-color);
}

.detail-score-label {
  font-size: 32rpx;
  color: var(--text-secondary);
  margin-left: 10rpx;
}

.detail-level {
  padding: 15rpx 30rpx;
  border-radius: 20rpx;
  margin-bottom: 30rpx;
  display: inline-block;
}

.detail-level-text {
  font-size: 28rpx;
  font-weight: 600;
}

.detail-date {
  margin-bottom: 30rpx;
  text-align: left;
}

.date-label {
  font-size: 28rpx;
  color: var(--text-secondary);
}

.date-value {
  font-size: 28rpx;
  color: var(--text-primary);
}

.detail-suggestions {
  text-align: left;
}

.suggestions-title {
  font-size: 32rpx;
  font-weight: 600;
  color: var(--text-primary);
  display: block;
  margin-bottom: 20rpx;
}

.suggestions-list {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.suggestion-item {
  font-size: 28rpx;
  color: var(--text-secondary);
  line-height: 1.4;
}

.modal-actions {
  display: flex;
  gap: 20rpx;
  padding: 20rpx 40rpx 40rpx;
}

.delete-btn, .retest-btn {
  flex: 1;
  padding: 24rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  border: none;
}

.delete-btn {
  background: #dc3545;
  color: white;
}

.retest-btn {
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
  color: white;
}
</style>